package cn.weekimwee.firstlineofcodeforkotlin.unit4

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.fragment_news_title.*
import kotlinx.android.synthetic.main.item_news.view.*
import org.jetbrains.anko.support.v4.startActivity

/**
 * Created by Wee Kim Wee on 2018/2/17.
 */
class NewsTitleFragment : Fragment() {

    var isTwoPane = false

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        return inflater?.inflate(R.layout.fragment_news_title, container, false)
    }

    private fun getNews(): MutableList<News> {
        val list = arrayListOf<News>()
        for(i in 0..50){
            list.add(News("title->$i","content->$i"))
        }
        return list
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        isTwoPane = activity.findViewById<View>(R.id.news_content_layout) != null
        news_title_recycler_view.apply {
            layoutManager = LinearLayoutManager(activity)
            val newAdapter = NewsAdapter()
            newAdapter.data = getNews()
            adapter = newAdapter

        }
    }

    inner class NewsAdapter : RecyclerView.Adapter<NewsAdapter.ViewHolder>() {

        var data: MutableList<News>? = null
            set(value) {
                field = value
                notifyDataSetChanged()
            }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent?.context).inflate(R.layout.item_news, parent, false)
            val viewHolder = ViewHolder(view)
            Log.e("eeeee","size-->${data?.size},position-->${viewHolder.adapterPosition}")
            val news = data?.get(viewHolder.adapterPosition+1) ?: News("nothing", "nothing")
            view.setOnClickListener {
                if (isTwoPane) {
                    (fragmentManager.findFragmentById(R.id.news_content_fragment) as NewsContentFragment).refresh(news.title, news.content)
                } else {
                    startActivity<NewsContentActivity>("title" to news.title, "content" to news.content)
                }
            }
            return viewHolder
        }

        override fun getItemCount(): Int {
            return data?.size ?: 0
        }

        override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
            val news = data?.get(position)
            holder?.titleText?.text = news?.title
        }

        inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val titleText = view.news_title
        }
    }
}